/**
 * FileUtils.java   2017年5月4日 上午11:50:12 by xuebing 
 *
 * Copyright (c) 2010 - 2017 All rights reserved.
 * 
 */
package com.rongmai.db.utils;


import com.rongmai.db.exception.BzException;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileUtils {

    /**
     * 适合小文件上传
     *
     * @Title uploadSmallFile
     * @param fileName
     * @param bytes
     * @return void
     *
     * @author xuebing.li
     * @date 2017年5月4日 上午11:36:05
     */
    public static void uploadSmallFile(String fileName, byte[] bytes) {
        try {
            BufferedOutputStream buffStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(fileName)));
            buffStream.write(bytes);
            buffStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static byte[] getImageFileInputStream(String imgUrl) throws IOException {
        if(StringUtils.isEmpty(imgUrl)) {
            throw new BzException("path为空");
        }
        ByteArrayOutputStream outStream = null;
        InputStream inStream = null;
        try {
            inStream = new FileInputStream(imgUrl);
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            return outStream.toByteArray();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (outStream != null) {
                    outStream.close();
                }
            } catch (Exception e2) {
                throw new RuntimeException("读取Aliyun的流的文件无法关闭");
            }
        }
    }
}
